package com.xy.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xy.constant.Constant;
import com.xy.entity.News;
import com.xy.entity.User;
import com.xy.service.NewsService;
import com.xy.util.DateStringUtil;
import com.xy.util.PropertiesUtil;
import com.xy.util.StringUtil;

@Controller
//@Scope(value="prototype")
public class NewsController {
	private Logger log = Logger.getLogger(NewsController.class);
	@Autowired
	private NewsService newsService;

	/**
	 * 添加新闻信息
	 * 
	 * @param news
	 * @param imgFile
	 * @param result
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "addNews", method = RequestMethod.POST)
	public String addNews(@Validated News news, @RequestParam("imagefile") CommonsMultipartFile imgFile, BindingResult result, Model model, HttpSession session) {
		User user = (User) session.getAttribute("myUser");
		news.setCreaterID(user.getID());
		news.setCreaterTime(new Date());
		Map<String, String> errorMap = new HashMap<String, String>();
		if (result.hasErrors()) {
			List<FieldError> fieldErrorList = result.getFieldErrors();
			for (FieldError fieldError : fieldErrorList) {
				String fieldName = fieldError.getField();// 属性名
				String errorMessage = fieldError.getDefaultMessage();// 错误信息
				log.info("fieldName:" + fieldName + ", errorMessage:" + errorMessage);
				errorMap.put(fieldName, errorMessage);
			}
		}
		// 图片上传处理
		String imgRealName = imgFile.getOriginalFilename();
		if (!StringUtil.isEmpty(imgRealName)) {
			// 新文件名
			String newImgName = DateStringUtil.getDateToString();
			// 文件后缀名
			String houZhui = imgRealName.substring(imgRealName.lastIndexOf("."));
			// 上传路径
			String path = PropertiesUtil.getValue(Constant.UPLOAD_PATH) + PropertiesUtil.getValue(Constant.NEWS_UPLOAD_PATH) + newImgName + houZhui;

			try {
				imgFile.transferTo(new File(path));
				news.setImgURL(PropertiesUtil.getValue(Constant.NEWS_UPLOAD_PATH) + newImgName + houZhui);
				news.setImgRealName(imgRealName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// -------------文件上传处理结束
		if (newsService.addNews(news)) {
			log.info("新闻添加成功；" + news);
			return "selectNews.action";
		}
		model.addAttribute("news", news);
		model.addAttribute("errorMap", errorMap);
		return "pages/backend/newsAdd.jsp";
	}

	/**
	 * 删除新闻信息
	 * 
	 * @param news
	 * @return
	 */
	@RequestMapping(value = "deleNews", method = RequestMethod.GET)
	public @ResponseBody
	String deleNews(News news) {
		if (!newsService.deleNews(news)) {
			return "error";
		}
		return "success";

	}

	/**
	 * 跳转到更新界面
	 * 
	 * @param news
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updateNews", method = RequestMethod.GET)
	public String updateNews(News news, Model model) {
		List<News> newsList = newsService.selectNews(news);
		news = newsList.get(0);
		model.addAttribute("news", news);
		return "pages/backend/newsModify.jsp";
	}

	/**
	 * 更新新闻信息
	 * 
	 * @param news
	 * @param model
	 * @param result
	 * @param modelMap
	 * @param imgFile
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "updateNewsAction", method = RequestMethod.POST)
	public String updateNewsAction(@Validated News news, Model model, BindingResult result, ModelMap modelMap, @RequestParam("imagefile") CommonsMultipartFile imgFile, HttpSession session) {
		User user = (User) session.getAttribute("myUser");
		news.setCreaterID(user.getID());
		news.setCreaterTime(new Date());

		Map<String, String> errorMap = new HashMap<String, String>();
		if (result.hasErrors()) {
			List<FieldError> errorList = result.getFieldErrors();
			for (FieldError fieldError : errorList) {
				// 属性名
				String errorName = fieldError.getField();
				// 错误信息
				String errorMessage = fieldError.getDefaultMessage();
				log.info("errorName:" + errorName + "   ,errorMessage:" + errorMessage);
				errorMap.put(errorName, errorMessage);
			}
		}
		// 图片上传处理
		String imgRealName = imgFile.getOriginalFilename();
		if (!StringUtil.isEmpty(imgRealName)) {

			// 新文件名
			String newImgName = DateStringUtil.getDateToString();
			// 文件后缀名
			String houZhui = imgRealName.substring(imgRealName.lastIndexOf("."));
			// 上传路径
			String path = PropertiesUtil.getValue(Constant.UPLOAD_PATH) + PropertiesUtil.getValue(Constant.NEWS_UPLOAD_PATH) + newImgName + houZhui;

			try {
				imgFile.transferTo(new File(path));
				news.setImgURL(PropertiesUtil.getValue(Constant.NEWS_UPLOAD_PATH) + newImgName + houZhui);
				news.setImgRealName(imgRealName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (newsService.updateNews(news)) {
			log.info("新闻更新成功；" + news);
			return "selectNews.action";
		}
		model.addAttribute("news", news);
		model.addAttribute("errorMap", errorMap);
		return "pages/backend/newsModify.jsp";
	}

	/**
	 * 查看新闻详情
	 * 
	 * @param news
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "selectNewsDetail", method = RequestMethod.GET)
	public String selectNewsDetail(News news, Model model) {
		List<News> newsList = newsService.selectNews(news);
		news = newsList.get(0);
		model.addAttribute("news", news);
		return "pages/backend/newsDetail.jsp";
	}

	/**
	 * 查询所有新闻信息
	 * 
	 * @param news
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "selectNews", method = { RequestMethod.GET, RequestMethod.POST })
	public String selectNews(News news, Model model) {
		List<News> newsList = newsService.selectNews(null);
		if (newsList != null && newsList.size() > 0) {
			model.addAttribute("newsList", newsList);
			return "pages/backend/newsManage.jsp";
		}
		return "pages/backend/newsManage.jsp";
	}
}
